package com.kaka.starter.mybatis.config;

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.kaka.starter.mybatis.properties.MyBaitsProperties;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.List;
import java.util.NoSuchElementException;

/**
 * 自动插入用户id使用
 *
 * @author kaka
 * @Date 2022/1/17
 */

public class DataSetValueInterceptor implements InnerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(DataSetValueInterceptor.class);

    private MyBaitsProperties myBaitsProperties;

    public DataSetValueInterceptor(MyBaitsProperties myBaitsProperties) {
        this.myBaitsProperties = myBaitsProperties;
    }

    @Override
    public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) {
        if (SqlCommandType.INSERT != ms.getSqlCommandType()) {
            return;
        }
        processParam(parameter);
    }

    private void processParam(Object parameterObject) {
        if (parameterObject instanceof MapperMethod.ParamMap) {
            try {
                List entityList = (List) ((MapperMethod.ParamMap) parameterObject).get("entityList");
                entityList.forEach(it -> processParamExec(it));
            } catch (Exception e) {
                //不需要批量插入默认属性
            }

        } else {
            processParamExec(parameterObject);
        }
    }

    private void processParamExec(Object parameterObject) {
        Class<?> clz = parameterObject.getClass();
        try {
            for (Field declaredField : clz.getDeclaredFields()) {
                //如果用户为空 则设置user
                if (declaredField.getName().equals(myBaitsProperties.getCreateUser())) {
                    declaredField.setAccessible(true);
                    if (declaredField.get(parameterObject) == null) {
                        //try {
                        //    final String userId = HeaderUtils.getUserId();
                        //    declaredField.set(parameterObject, userId);
                        //} catch (NoSuchMethodError error) {
                        //    //没有用户登录什么都不做
                        //    logger.warn("[BIZ] create_user not set because user id not found ");
                        //}
                    }
                } else if (declaredField.getName().equals(myBaitsProperties.getCreateTime())) {
                    declaredField.setAccessible(true);
                    if (declaredField.get(parameterObject) == null) {
                        declaredField.set(parameterObject, LocalDateTime.now().withNano(0));
                    }
                }else if (declaredField.getName().equals(myBaitsProperties.getTenantId())) {
                    declaredField.setAccessible(true);
                    if (declaredField.get(parameterObject) == null) {
                        //try {
                        //    final Integer tenantId = HeaderUtils.getTenantId();
                        //    declaredField.set(parameterObject, tenantId);
                        //} catch (NoSuchMethodError error) {
                        //    //没有租户什么都不做
                        //    logger.warn("[BIZ] tenantId not set because tenant id not found ");
                        //}
                    }
                }
            }
        } catch (IllegalAccessException e) {
            throw new NoSuchElementException("IllegalAccessException error is " + e.getMessage());
        }
    }
}
